/*
 * Copyright (C) 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package android.com.app;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


/********* DBAdapter class
         * Defines all the methods for database operations
         * Allows for insertion, updation and deletion of entries
         */

public class DBAdapter{

	//Access tables using this enum //
	public enum  Table{TAGS,AUDIO};
	public static final String[] TagTableAttribs = {"title","posx1","posy1","posx2","posy2","tag","_id"}; 
    public static final String[] AudioTableAttribs = {"title","audio"};
    private static final String TAG = "ApicDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
      
    private static final String DATABASE_NAME = "apicdata";
    private static final String TAG_TABLE = "apictags";
    private static final String AUD_TABLE = "apicaudio";
    
    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL( "create table " + AUD_TABLE + "(_id integer primary key autoincrement, "
                    + "title text not null, audio string);");
            db.execSQL( "create table " + TAG_TABLE + "(_id integer primary key autoincrement, "
                    + "title text not null, posx1 float, posy1 float, posx2 float, posy2 float, tag string);");      
            
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }

    public DBAdapter(Context ctx) {
        this.mCtx = ctx;
    }
    

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * Throws SQLException if the database could be neither opened or created
     */
    public DBAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
      
    public void close() {
        mDbHelper.close();
    }

    /******** Add audio entry *************/
   	
    public long AddAudio(String imgtitle,String imgaudio) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(AudioTableAttribs[0], imgtitle);
        initialValues.put(AudioTableAttribs[1], imgaudio);
        return mDb.insert(AUD_TABLE, null, initialValues);
    }
    
  
    
    /****** Add Tag Entry ***********/
    
    public long AddTag(float x1, float y1, float x2, float y2, String tagn, String id) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(TagTableAttribs[0], id);
        initialValues.put(TagTableAttribs[1], x1);
        initialValues.put(TagTableAttribs[2], y1);
        initialValues.put(TagTableAttribs[3], x2);
        initialValues.put(TagTableAttribs[4], y2);        
        initialValues.put(TagTableAttribs[5], tagn);
        return mDb.insert(TAG_TABLE, null, initialValues);
    }


    public Cursor fetchAll(Table tablename) {
    	
    	switch(tablename){
    	
    	case AUDIO:        
    		return mDb.query(AUD_TABLE, AudioTableAttribs, null, null, null, null, null);

    	case TAGS:
            return mDb.query(TAG_TABLE, TagTableAttribs, null, null, null, null, null);

        default:
        	return null;
    	
    	}

    }

  
    public Cursor fetch(Table tablename,String title) throws SQLException {

        Cursor mCursor = null;
        boolean exflag=false;
        
        try {
        	
        	switch(tablename){
        	
        	case AUDIO:
        		mCursor= mDb.query(true, AUD_TABLE, AudioTableAttribs, AudioTableAttribs[0] + "= '" +title+"'", null,
                        null, null, null, null);
        		break;
        	
        	case TAGS:
        		mCursor= mDb.query(true, TAG_TABLE, TagTableAttribs, TagTableAttribs[0] + "= '" +title+"'", null,
                        null, null, null, null);
        		break;
              
            default:
            	break;
              
        	}
                 
        }catch(Exception e) {
        	exflag=true;
        }
        
        if (mCursor.getCount()>0 && !exflag) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    
   
    public int DeleteTable(Table tablename) {
    	
    	switch(tablename){
    	
    	case AUDIO: 
    		return mDb.delete(AUD_TABLE, null, null);
    	case TAGS: 
    		return mDb.delete(TAG_TABLE, null, null);
    	default: 
    		return 0;
    	
    	}
    	
    }	
    
    public boolean DeleteEntry(Table tablename,String keyid) {

    	switch(tablename){
    	
    	case AUDIO: 
    		return mDb.delete(AUD_TABLE, AudioTableAttribs[0] + "=" + keyid, null) > 0;
      	case TAGS: 
      		return mDb.delete(TAG_TABLE, TagTableAttribs[0] + "=" + keyid, null) > 0;
      	default: 
      		return false;
    	}
    
    }
    
    
    public boolean DeleteEntry(Table tablename,String keyid, int tagID) {

    	switch(tablename){
    	
    	case AUDIO: 
    		return false;
      	case TAGS: 
      		return mDb.delete(TAG_TABLE, TagTableAttribs[0] + "='" + keyid+"' AND "+
      				TagTableAttribs[6] + "='" + tagID+"'", null) > 0;
      	default: 
      		return false;
    	}
    
    }

    public boolean updateNote(String keytitle, int oldtag, String newTag, Table tablename) {

    	ContentValues args = new ContentValues();
    	boolean exflag=false;
    	Cursor mCursor=null;
    	
    	switch(tablename) {
    	
    	case AUDIO:
    	break;
    	
    	
    	case TAGS:
    	try {
    		mCursor=
    			mDb.query(true, TAG_TABLE, TagTableAttribs, "title" + "='" + keytitle+"' AND "+"_id"+"=" + oldtag, null,
    					null, null, null, null);
    	}catch(Exception e) {
    		//Log.i("upd",e.toString());
    		exflag=true;
    	}

    	if (mCursor.getCount()<=0 || exflag) {
    		return false;            
    	}
    	else {
    		mCursor.moveToFirst();
    		args.put("tag", newTag);
    		return mDb.update(TAG_TABLE, args, "_id"+ "=" + oldtag, null) > 0;
    	}
    	}
    	
    	return false;
    }
   
    
}
